#!/usr/bin/env python

import socket
import sys
import array
import struct

## Global Variables... I know this is not proper programming but I don't care

byte0 = chr(0xFF)
byte1 = chr(0x00)
id1 = chr(0x1e)
id2 = chr(0x19)
id3 = chr(0x0d)

fwd = chr(0x05)
rev = chr(0x0a)
dir1 = ''
dir2 = ''
dir3 = ''

#transmitB = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def alert(msg):
	print >>sys.stderr, msg
	sys.exit(1)

def connectSrv():
	host = '192.168.1.138'
	port = 50004
	size = 100
	
	try:
		s.connect((host,port))
		print '\nConnecting to server...\n'
	except Exception, e:
		alert('Something is wrong with %s:%d. Exception is type %s' % (host, port, e))
	print 'Connection Established!!!\n'

def txBender(transmit):
	print 'Sending %s over tubes\n' % (transmit)
	s.send(transmit)

def wButton(m1, m2, m3):
	global  dir1, dir2, dir3
	m1 += int(m1 + 5)
	dir1 = chr(0x05)
	m2 = int(0)
	dir2 = chr(0x05)
	m3 += int(m2 + 5)
	dir3 = chr(0x06)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = chr(transmit + x)
	txBender(transmit)

def sButton(m1, m2, m3):
	global dir1, dir2, dir3
	m1 += chr(0x05)
	dir1 = chr(0x06)
	m2 = chr(0x00)
	dir2 = chr(0x06)
	m3 += chr(0x05)
	dir3 = chr(0x05)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

def dButton(m1, m2, m3):
	global dir1, dir2, dir3
	m1 = chr(m1 + 0x05)
	dir1 = chr(0x06)
	m2 = chr(0x00)
	dir2 = chr(0x06)
	m3 = chr(m3 + 0x05)
	dir3 = chr(0x06)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

def aButton(m1, m2, m3):
	global dir1, dir2, dir3
	m1 = chr(m1 + 0x05)
	dir1 = chr(0x06)
	m2 = chr(m2 + 0x05)
	dir2 = chr(0x06)
	m3 = chr(0x20)
	dir3 = chr(0x06)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

def stp(m1, m2, m3):
	global dir1, dir2, dir3
	m1 = chr(0x00)
	dir1 = chr(0x0a)
	m2 = chr(0x00)
	dir2 = chr(0x0a)
	m3 = chr(0x00)
	dir3 = chr(0x0a)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

def main():	
	running = 1
	m1 = int(0)
	m2 = int(0)
	m3 = int(0)

	dir1 = ''
	dir2 = ''
	dir3 = ''

	while running:
		choice = raw_input('\n...you know the commands...\n')
		if choice == 'w':
			wButton(m1, m2, m3)
		elif choice == 's':
			sButton(m1, m2, m3)
		elif choice == 'a':
			aButton(m1, m2, m3)
		elif choice == 'd':
			dButton(m1, m2, m3)
		elif choice == 'st':
			stp(m1, m2, m3)
		else:
			print 'Exiting...\n'
			running = 0
	s.close()
	exit()

connectSrv()
main()
